package com.yonyou.wdt.web;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.wdt.crypto.EncryptionHolder;
import com.yonyou.wdt.crypto.EventCrypto;
import com.yonyou.wdt.crypto.PrivateAppCrypto;
import com.yonyou.wdt.entity.EventContent;;
import com.yonyou.wdt.qimenmodel.taobao.api.internal.toplink.embedded.websocket.handshake.Handshake;
import com.yonyou.wdt.service.impl.SyncProductInsertImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;

/**
 * 处理用友开放平台推送的数据变更事件。
 * <ul>
 *     <li>处理成功后需回复 <code>success</code>，否则开放平台视为推送失败，会进行重试</li>
 *     <li>耗时操作推荐异步处理，平台默认推送超时时间为 5 秒，超时视为推送失败</li>
 *     <li>推送失败后开放平台会进行重试投递，重试策略为每分钟一次，每5分钟一次，每一小时一次，直到 24 小时，超过 24 小时仍未成功成功的不再尝试</li>
 * </ul>
 */
@Component
@RestController
public class PushController {

    @Value("${ys.config.appKey}")
    private String appKey;
    @Value("${ys.config.appSecret}")
    private String appSecret;
    
    private static final Logger logger = LoggerFactory.getLogger(PushController.class);

    @Resource
    private SyncProductInsertImpl syncProductInsert;
    
    private ObjectMapper mapper = new ObjectMapper();
    public static final String aesKey = "JuShuiTanConnectordas4et8ga4ae58";

    public static final SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, aesKey.getBytes(CharsetUtil.CHARSET_UTF_8));

    @PostMapping("/getQiMenData")
    public JSONObject getQiMenData(@RequestBody String holder) throws IOException {
        String s = aes.decryptStr(holder,CharsetUtil.CHARSET_UTF_8);
        JSONObject entries = new JSONObject();
        if (JSONUtil.parseObj(s).getStr("password").equals("allt123")){
            entries.set("status","200");
            entries.set("serverUrl","http://hu3cgwt0tc.api.taobao.com/router/qm");
            entries.set("appKey","34351842");
            entries.set("appSecret","8df12ded8c1652df1f995ae6c5e40069");
            entries.set("targetAppKey","21363512");
            return entries;
        }
        return entries;
    }

    public static void main(String[] args) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("password","allt123");
        String s = aes.encryptHex(JSONUtil.toJsonStr(stringObjectHashMap));
        System.out.println(s);
    }
    @PostMapping("/eventPush")
    public String eventCallBackReceiver(@RequestBody EncryptionHolder holder) throws IOException {
        // 构建解密验签处理对象
        EventCrypto crypto = PrivateAppCrypto.newCrypto(appKey, appSecret);
        // 验签解密后的消息体
        String decryptMessage = crypto.decryptMsg(holder);
        // 反序列化后的消息内容对象
        EventContent content = mapper.readValue(decryptMessage, EventContent.class);
        logger.info("新的事件推送，content: {}", content.toString());
        // 根据事件类型进行相关处理操作，耗时操作推荐异步处理，平台默认推送超时时间为 5 秒，超时视为推送失败
        // 事件订阅请求详细信息
        String contentData = content.getContent();
        // logger.info("事件订阅请求信息体：【\n{}\n】", contentData);
        switch (content.getType()) {
            case CHECK_URL:
                // logger.info("事件类型: {}, 说明: 检查事件推送回调地址", EventType.CHECK_URL);
                // TODO: 2024/8/23  异步执行业务代码，执行时长可超五秒
                syncProductInsert.checkAsync();
                break;
            case YXYBASEDOC_PC_PRODUCT_INSERT:
                // logger.info("事件类型: {}, 说明: 租户 {} 下物料档案新增，信息: {}", content.getType(), content.getTenantId(), content.getContent());
                syncProductInsert.productInsert(contentData);
                break;
            case YXYBASEDOC_PC_PRODUCT_UPDATE:
                // logger.info("事件类型: {}, 说明: 租户 {} 下物料档案新增，信息: {}", content.getType(), content.getTenantId(), content.getContent());
                syncProductInsert.productUpdate(contentData);
                break;
            case BASEDOC_VENDOR_ADD_AFTER:
                // logger.info("事件类型: {}, 说明: 租户 {} 下物料档案新增，信息: {}", content.getType(), content.getTenantId(), content.getContent());
                syncProductInsert.vendorAddAsync(contentData);
                break;
            case BASEDOC_VENDOR_UPDATE_AFTER:
                // logger.info("事件类型: {}, 说明: 租户 {} 下物料档案新增，信息: {}", content.getType(), content.getTenantId(), content.getContent());
                syncProductInsert.vendorUpdateAsync(contentData);
                break;
            case UNKNOWN:
                logger.info("未知事件");
                break;
            default:
                logger.info("");
        }
        // 处理成功，回复 "success" 告知开放平台，否则开放平台会重试推送，直到 24 小时
        return "success";
    }
    
}
